//
//  AppDelegate.m
//  WeKeTang
//
//  Created by ichina on 2017/8/21.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "AppDelegate.h"
#import <AFNetworkReachabilityManager.h>
#import "UMMobClick/MobClick.h"
#import "WKDrawerViewController.h"
#import "WKHomeViewController.h"
#import "WKLoginViewController.h"
#import "WKNavgationController.h"
#import "WKLunchImageTools.h"
#import "WKGuideViewController.h"
#import "WKProfireViewController.h"
#import "WKUniversal.h"
#import "WKLoginHandel.h"
#import "WXApi.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WKFMDBTools.h"
#import "Reachability.h"
#import "UMessage.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<WXApiDelegate,QQApiInterfaceDelegate,UNUserNotificationCenterDelegate>

@property (nonatomic, strong) WKFMDBTools *dbManger;

@property (nonatomic, strong) WKDrawerViewController *drawVc;

@end

@implementation AppDelegate

+ (AppDelegate *)shareDelegate{
    
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //第一次进入程序时和版本升级时要加载引导也
    //先获取当前的版本号
    if (isPad) { 
        [WKUniversal showInfo:@"当前应用不支持iPad"];
        return NO;
    }
    NSString *str =[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    //再读区本地存储的版本好
    NSUserDefaults *defauls =[NSUserDefaults standardUserDefaults];
    NSString *verson =[defauls objectForKey:@"AppVersion"];
    NSLog(@"版本号:%@------%@",str,verson);
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //检测网络环境
    [self checkReachabilityStatus];
    //对比版本好 如果版本号一样 就到登录控制器 否则加载引导页
    if ([str isEqualToString:verson]){
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"account"]  && [[NSUserDefaults standardUserDefaults]objectForKey:@"psd"] && ![[[NSUserDefaults standardUserDefaults]objectForKey:@"account"] isEqualToString:@""] && ![[[NSUserDefaults standardUserDefaults]objectForKey:@"psd"] isEqualToString:@""] ) {
            NSLog(@"====%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"account"]);
            
            WKHomeViewController *mainVC = [[WKHomeViewController alloc] init];
            mainVC.userId = [WKLoginHandel getLoginDataWithString:@"userid"];
            WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:mainVC];
            
            self.window.rootViewController = navVC;
        }else{
            WKLoginViewController *loginVC = [[WKLoginViewController alloc]init];
            WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:loginVC];
            self.window.rootViewController = navVC;
        }
       
    }else{
        //进入引导页
        WKGuideViewController *guideVC = [[WKGuideViewController alloc]init];
        self.window.rootViewController = guideVC;
        [defauls setObject:str forKey:@"AppVersion"];
        [defauls synchronize];
    }
    //分享shareSDK
    [self setShareSDK];
    //设置启动图
    [WKLunchImageTools animWithWindow:self.window image:nil];
    //友盟统计
    UMConfigInstance.appKey = UMAppKey;
    UMConfigInstance.channelId = @"App Store";
    UMConfigInstance.eSType = E_UM_GAME; //仅适用于游戏场景，应用统计不用设置
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    //友盟推送
    [UMessage openDebugMode:YES];
    [UMessage startWithAppkey:@"599ced634544cb17c700017a" launchOptions:launchOptions httpsEnable:YES];
    //注册通知，如果要使用category的自定义策略，可以参考demo中的代码。
    [UMessage registerForRemoteNotifications];
    //iOS10必须加下面这段代码。
    if (@available(iOS 10.0, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
         center.delegate=self;
        UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
        [center requestAuthorizationWithOptions:types10     completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                //点击允许
                //这里可以添加一些自己的逻辑
            } else {
                //点击不允许
                //这里可以添加一些自己的逻辑
            }
        }];
    } else {
        // Fallback on earlier versions
    }
    
    [UMessage setLogEnabled:YES];

    
    //微信登录
    [WXApi registerApp:kWxAppID];
    
    self.dbManger = [WKFMDBTools defaultFMDBToos];
//    初始化数据库
//    创建下载表
    [self.dbManger creatTableDownload];
//    创建观看视频表
    [self.dbManger creatTableWatchRecode];
    
    //设置全局状态栏颜色为白色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [self.window makeKeyAndVisible];
    
    return YES;
}
- (void)setShareSDK{
    
    NSArray *Platforms = @[
                           @(SSDKPlatformTypeWechat),
                           @(SSDKPlatformTypeQQ)
                           ];
    [ShareSDK registerActivePlatforms:Platforms onImport:^(SSDKPlatformType platformType) {
        
        switch (platformType) {
            case SSDKPlatformTypeWechat:
                [ShareSDKConnector connectWeChat:[WXApi class]];
                break;
            case SSDKPlatformTypeQQ:
                [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                break;
            default:
                break;
        }
        
    } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
        
        switch (platformType) {
            case SSDKPlatformTypeWechat:
                [appInfo SSDKSetupWeChatByAppId:kWxAppID
                                      appSecret:kWxAppSecret];
                break;
            case SSDKPlatformTypeQQ:
                [appInfo SSDKSetupQQByAppId:kQQAppID
                                     appKey:kQQAppSecret
                                   authType:SSDKAuthTypeBoth];
            default:
                break;
        }
    }];
    
}
//iOS10以下使用这个方法接收通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    [UMessage didReceiveRemoteNotification:userInfo];
    
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    
    NSLog(@"deviceToken:%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                             stringByReplacingOccurrencesOfString: @">" withString: @""]
                            stringByReplacingOccurrencesOfString: @" " withString: @""]);
    // 1.2.7版本开始不需要用户再手动注册devicetoken，SDK会自动注册
    [UMessage registerDeviceToken:deviceToken];
}
//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //关闭U-Push自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //应用处于后台时的远程推送接受
            //必须加这句代码
            [UMessage didReceiveRemoteNotification:userInfo];
            
        }else{
            //应用处于后台时的本地推送接受
        }
    } else {
        // Fallback on earlier versions
    }
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    NSLog(@"scheme====%@",[url scheme]);
    if (!url) {
        return NO;
    }    
    if ([[url scheme] isEqualToString:kQQUrlSchema]) {
        
        [QQApiInterface handleOpenURL:url delegate:self];
        
        return [TencentOAuth HandleOpenURL:url];
    }
    
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    NSLog(@"scheme====%@",[url scheme]);
    if (!url) {
        return NO;
    }
    if ([[url scheme] isEqualToString:kQQUrlSchema]) {
        
        [QQApiInterface handleOpenURL:url delegate:self];
        
        return [TencentOAuth HandleOpenURL:url];
    }
    return [WXApi handleOpenURL:url delegate:self];
    
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    NSLog(@"scheme====%@",[url scheme]);
    if (!url) {
        return NO;
    }
    
    if ([[url scheme] isEqualToString:kQQUrlSchema]) {
        
        [QQApiInterface handleOpenURL:url delegate:self];
        
        return [TencentOAuth HandleOpenURL:url];
    }
    [WXApi handleOpenURL:url delegate:self];
    
    return YES;
}


#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    
    if ([resp isKindOfClass:[SendAuthResp class]]){
        SendAuthResp *rep = (SendAuthResp *)resp;
        if (rep.errCode == 0) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WXLoginSuccess" object:@{@"code":rep.code}];
            
        }else if (rep.errCode == -4){
            NSLog(@"用户拒绝授权");
            [WKUniversal showInfo:@"您已拒绝授权"];
            
        }else if (rep.errCode == -2){
            NSLog(@"用户取消");
            [WKUniversal showInfo:@"您已取消微信登录"];
        }
    }
}
/**
 处理来至QQ的请求
 */
- (void)onReq:(QQBaseReq *)req{
    NSLog(@" ----req %@",req);
}
/**
 处理QQ在线状态的回调
 */
- (void)isOnlineResponse:(NSDictionary *)response{
    
}
//检测网络环境
- (void)checkReachabilityStatus {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusNotReachable) {
            // 无网络
            [AppDelegate shareDelegate].reachabilityStatus = 0;
            WKLoginViewController *loginVC = [[WKLoginViewController alloc]init];
            WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:loginVC];
            [[UIApplication sharedApplication] delegate].window.rootViewController = navVC;
            
        }else if (status == AFNetworkReachabilityStatusReachableViaWiFi){
            // wifi
            [AppDelegate shareDelegate].reachabilityStatus = 2;
            
        }else if (status == AFNetworkReachabilityStatusReachableViaWWAN) {
            // 移动网络
            [AppDelegate shareDelegate].reachabilityStatus = 1;
            
        }else {
            // 未知网络
            [AppDelegate shareDelegate].reachabilityStatus = -1;
            
        }
    }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

// 禁止横屏
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.allowRotation) {
        
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
